﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.MenuCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.MenuHandler
{
    /// <summary>
    /// 修改菜单命令处理类
    /// </summary>
    public class UpdMenuHandler : IRequestHandler<UpdMenuCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Menu> menuRep;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="menuRep"></param>
        /// <param name="mapper"></param>
        public UpdMenuHandler(IBaseRepository<Menu> menuRep,IMapper mapper)
        {
            this.menuRep = menuRep;
            this.mapper = mapper;
        }

        public  Task<APIResult<int>> Handle(UpdMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var model = mapper.Map<Menu>(request);
            var name =  menuRep.GetAll().Where(x=>x.PId==request.PId&&x.MenuName==request.MenuName);
            if (name.Count()>0)
            {
                result.Code = APIEnum.Failed;
                result.Msg = $"同一级菜单下已存在{request.MenuName}的名称,不能修改";
                result.Data = 0;
                return  Task.FromResult(result);
            }
            model.UpdateUser = "张三";
            model.UpdateTime = DateTime.Now;

             menuRep.Update(model);
            result.Code = APIEnum.Success;
            result.Msg = "修改成功";
            result.Data = 1;
            return  Task.FromResult(result);

        }
    }
}
